/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package DatabazoveOkno;

import HlavneOkno.Okno;
import java.awt.Toolkit;
import java.awt.TrayIcon;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.*;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.event.InternalFrameEvent;
import javax.swing.event.InternalFrameListener;

/**
 *
 * @author Riso-Desktop
 */
public class DatabazoveOkno extends javax.swing.JInternalFrame implements InternalFrameListener {

    Connection conn = null;
    Statement st = null;
    ResultSet resultSet;
    ResultSet rs = null;
    DatabaseMetaData dbmd = null;
    ResultSetMetaData rsmd = null;
    Tabulka tabulka;
    JFrame frame;
    int pocetprepnuti = 0;
    String meno;
    String databaza;
    String staryNazovJboxu; //pre porovnávanie názvov
    ArrayList<String> nazvyStlpcov = null; //posiela sa do comboboxu vo filtry
    public static int zobrazeniex = 0;
    public static int zobrazeniey = 0;
    public static int pocetokien = 0;
    public static JDesktopPane deskpane;
    public String nazovtabulky;

    /**
     * Creates new form DatabazoveOkno
     */
    public DatabazoveOkno(Connection conn, JFrame frame) {
        initComponents();
        this.conn = conn;
        jTable1.setShowGrid(true);
        this.frame = frame;
        nacitajDatabazu();
        nacitajTabulky();
        pridajMouselistener();
        pridajTriedenie();
        this.addInternalFrameListener(this);
    }

    private void nacitajDatabazu() {
        try {
            st = conn.createStatement();
            dbmd = conn.getMetaData();
        } catch (Exception ex) {
            Logger.getLogger("mojlog").log(Level.WARNING,ex.toString(),ex);
        }
    }

    private void nacitajTabulky() {
        jComboBox1.removeAllItems();
        try {
            String[] types = {"TABLE"};
            resultSet = dbmd.getTables(null, null, "%", types);
            while (resultSet.next()) {
                jComboBox1.addItem(resultSet.getString(3));
            }
            resultSet.first();
            this.setTitle(resultSet.getString(1) + " - " + jComboBox1.getSelectedItem().toString());
            databaza = resultSet.getString(1);
            tabulka = new Tabulka(st, jComboBox1.getSelectedItem().toString());
            jTable1.setModel(tabulka);
            nazovtabulky = jComboBox1.getSelectedItem().toString(); 
        } catch (Exception ex) {
            Logger.getLogger("mojlog").log(Level.WARNING,ex.toString(),ex);
        }
    }

    private void novaPozicia() {
        if (deskpane != null) {
            int x = deskpane.getWidth();
            int y = deskpane.getHeight();
            this.setLocation((zobrazeniex * 40), (zobrazeniey * 20));
            if (zobrazeniex * 40 > x / 2) {
                zobrazeniey = zobrazeniey / 3;
                zobrazeniex = 0;
            }
            if (zobrazeniey * 40 > y / 2) {
                zobrazeniey = 0;
                zobrazeniex = zobrazeniex / 3;
            }
        }
        zobrazeniex++;
        zobrazeniey++;
        pocetokien++;
    }

    private void pridajTriedenie() {
        jTable1.setAutoCreateRowSorter(true);
    }

    private void pridajMouselistener() {
        jTable1.addMouseListener(new MouseAdapter() {

            @Override
            public void mousePressed(MouseEvent e) {
                if (e.getButton() == MouseEvent.BUTTON3) {
                    if (jTable1.getSelectedRowCount() > 1) {
                        ZmenitZaznam.setText("Zmeniť záznamy");
                    } else {
                        ZmenitZaznam.setText("Zmeniť záznam");
                    }
                    jPopupMenu1.show(jTable1, e.getX(), e.getY());
                }
            }
        });
    }

    public ArrayList getNazvyStlpcov() {
        nazvyStlpcov = new ArrayList<String>();
        for (int i = 0; i < tabulka.getColumnCount(); i++) {
            nazvyStlpcov.add(tabulka.getColumnName(i));
        }
        return nazvyStlpcov;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPopupMenu1 = new javax.swing.JPopupMenu();
        ZmenitZaznam = new javax.swing.JMenuItem();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jToolBar1 = new javax.swing.JToolBar();
        jLabel1 = new javax.swing.JLabel();
        jComboBox1 = new javax.swing.JComboBox();
        jSeparator1 = new javax.swing.JToolBar.Separator();
        Filter = new javax.swing.JButton();
        jToolBar2 = new javax.swing.JToolBar();
        UpravOznacene = new javax.swing.JButton();
        VlozZaznam = new javax.swing.JButton();

        ZmenitZaznam.setText("Zmeniť záznam");
        ZmenitZaznam.setToolTipText("");
        ZmenitZaznam.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ZmenitZaznamActionPerformed(evt);
            }
        });
        jPopupMenu1.add(ZmenitZaznam);

        setClosable(true);
        setIconifiable(true);
        setMaximizable(true);
        setResizable(true);

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                jTable1MousePressed(evt);
            }
        });
        jScrollPane1.setViewportView(jTable1);

        jToolBar1.setFloatable(false);
        jToolBar1.setRollover(true);
        jToolBar1.setBorderPainted(false);

        jLabel1.setText("Tabuľky:");
        jToolBar1.add(jLabel1);

        jComboBox1.setMaximumSize(new java.awt.Dimension(150, 32767));
        jComboBox1.setMinimumSize(new java.awt.Dimension(150, 20));
        jComboBox1.setPreferredSize(new java.awt.Dimension(150, 20));
        jComboBox1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBox1ActionPerformed(evt);
            }
        });
        jToolBar1.add(jComboBox1);
        jToolBar1.add(jSeparator1);

        Filter.setText("Filter");
        Filter.setFocusable(false);
        Filter.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        Filter.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        Filter.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                FilterActionPerformed(evt);
            }
        });
        jToolBar1.add(Filter);

        jToolBar2.setFloatable(false);
        jToolBar2.setRollover(true);
        jToolBar2.setBorderPainted(false);

        UpravOznacene.setText("Upraviť označené");
        UpravOznacene.setFocusable(false);
        UpravOznacene.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        UpravOznacene.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        UpravOznacene.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                UpravOznaceneActionPerformed(evt);
            }
        });
        jToolBar2.add(UpravOznacene);

        VlozZaznam.setText("Vložiť nové záznamy");
        VlozZaznam.setFocusable(false);
        VlozZaznam.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        VlozZaznam.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        VlozZaznam.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                VlozZaznamActionPerformed(evt);
            }
        });
        jToolBar2.add(VlozZaznam);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jToolBar1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jToolBar2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 607, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jToolBar2, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 384, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    public void ukazTab(String meno) {
        try {
            tabulka = new Tabulka(st, meno);
            jTable1.setModel(tabulka);
            this.setTitle(resultSet.getString(1) + " - " + meno);
            jComboBox1.setSelectedItem(meno);
            this.meno = meno;
        } catch (SQLException ex) {
            Logger.getLogger("mojlog").log(Level.WARNING,ex.toString(),ex);
        }
    }
    private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox1ActionPerformed

        if (jComboBox1.getItemCount() != 0) {
            try {
                tabulka = new Tabulka(st, jComboBox1.getSelectedItem().toString());
                jTable1.setModel(tabulka);
                this.setTitle(resultSet.getString(1) + " - " + jComboBox1.getSelectedItem().toString());
                if (meno != null && Okno.nazvyZobraz.size() != 0 && pocetprepnuti > 1) {
                    nazovtabulky = jComboBox1.getSelectedItem().toString(); 
                    zmenNazovVOkno(meno, nazovtabulky); //zmeni nazvy otvorených tabuliek v hlavnom okne
                }else{
                    nazovtabulky = jComboBox1.getSelectedItem().toString(); 
                }
                this.meno = jComboBox1.getSelectedItem().toString();
                pocetprepnuti++;
            } catch (SQLException ex) {
                Logger.getLogger("mojlog").log(Level.WARNING,ex.toString(),ex);
            }
        }
    }//GEN-LAST:event_jComboBox1ActionPerformed

    private void zmenNazovVOkno(String nazov, String novy) {
        for (int i = 0; i < Okno.nazvyZobraz.size(); i++) {
            if (Okno.nazvyZobraz.get(i).equals(nazov)) {
                Okno.nazvyZobraz.remove(i);
                Okno.nazvyZobraz.add(novy);
            }
        }
    }

    private void vymazNazovVOkno(String nazov) {
        for (int i = 0; i < Okno.nazvyZobraz.size(); i++) {
            if (Okno.nazvyZobraz.get(i).equals(nazov)) {
                Okno.nazvyZobraz.remove(i);
            }
        }
    }

    private int getColumnInt(String col) {
        int a = -1;
        for (int i = 0; i < jTable1.getColumnCount(); i++) {
            if (jTable1.getColumnName(i).equals(col)) {
                a = i;
            }
        }
        return a;
    }

    public String getMeno() {
        return meno;
    }
    private void ZmenitZaznamActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ZmenitZaznamActionPerformed
        
        int[] zaznami = jTable1.getSelectedRows();
        String nazovid = null;
        try {
            ResultSet res = dbmd.getPrimaryKeys(null, null, jComboBox1.getSelectedItem().toString());
            int poc = res.getMetaData().getColumnCount();
            int id = -1;
            int[] rows = jTable1.getSelectedRows();
            ArrayList idcka = new ArrayList();
            StringBuilder sb = new StringBuilder();
            res = dbmd.getPrimaryKeys(null, null, jComboBox1.getSelectedItem().toString());
            
            while (res.next()) {
                //primarny kľuč
                nazovid = res.getString(4);
                for (int i = 0; i < rows.length; i++) {
                    id = (int) jTable1.getValueAt(rows[i], getColumnInt(nazovid));
                    idcka.add(id);
                }
            }
            for (int i = 0; i < idcka.size(); i++) {
                sb.append(idcka.get(i));
                if(i!=idcka.size()-1)sb.append(" or "+nazovid+" = ");
            }
            String sql = "Select * from "+ nazovtabulky + " where " + nazovid + " = " + sb.toString();
            System.out.println(sql);
            new upravaZaznamu(frame, st, nazovtabulky, sql, true, nazovid).setVisible(true);
            tabulka.reload();
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(rootPane,"Nieje možné vykonať update.");
            Logger.getLogger("mojlog").log(Level.WARNING,ex.toString(),ex);
        }
    }//GEN-LAST:event_ZmenitZaznamActionPerformed

    private void FilterActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_FilterActionPerformed
        Filter f = new Filter(frame, closable, this);
        f.setVisible(true);
        if(f.getSQL()!=null){
        tabulka = new Tabulka(st, jComboBox1.getSelectedItem().toString(),f.getSQL());
        jTable1.setModel(tabulka);
        }
    }//GEN-LAST:event_FilterActionPerformed

    private void jTable1MousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MousePressed
        // TODO add your handling code here:
        
    }//GEN-LAST:event_jTable1MousePressed

    private void UpravOznaceneActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_UpravOznaceneActionPerformed
        // TODO add your handling code here:
        if(jTable1.getSelectedRow()<0){
            Toolkit.getDefaultToolkit().beep();
            return;
        }
        ZmenitZaznamActionPerformed(evt);
    }//GEN-LAST:event_UpravOznaceneActionPerformed

    private void VlozZaznamActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_VlozZaznamActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_VlozZaznamActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton Filter;
    private javax.swing.JButton UpravOznacene;
    private javax.swing.JButton VlozZaznam;
    private javax.swing.JMenuItem ZmenitZaznam;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPopupMenu jPopupMenu1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JToolBar.Separator jSeparator1;
    private javax.swing.JTable jTable1;
    private javax.swing.JToolBar jToolBar1;
    private javax.swing.JToolBar jToolBar2;
    // End of variables declaration//GEN-END:variables

    @Override
    public void internalFrameOpened(InternalFrameEvent e) {
        novaPozicia();
    }

    @Override
    public void internalFrameClosing(InternalFrameEvent e) {
    }

    @Override
    public void internalFrameClosed(InternalFrameEvent e) {
        vymazNazovVOkno(meno);
    }

    @Override
    public void internalFrameIconified(InternalFrameEvent e) {
    }

    @Override
    public void internalFrameDeiconified(InternalFrameEvent e) {
    }

    @Override
    public void internalFrameActivated(InternalFrameEvent e) {
        deskpane = this.getDesktopPane();
    }

    @Override
    public void internalFrameDeactivated(InternalFrameEvent e) {
    }
}
